<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserController
 *
 * @author Windy
 */
class Core_UserController extends Zend_Controller_Action {

    public function loginAction() {

        $userModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getUserModel();
//        $bannerModel->setDbConnection($conn);
//        $users = $bannerModel->getAllUsers();
        $users = $userModel->getAllUsers();
        $this->view->assign('users', $users);
    }

    public function listAction() {

        $request = $this->getRequest();

        $userModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getUserModel();
        //$roleModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getRoleModel();

        /**
         * Get roles
         */
        //$roles = $roleModel->getRoles();

        /**
         * Get users
         */
        //$perPage = 15;
        //$query 	 = $request->getParam('query', '');
        //$params  = array();
        //if ($query == '') {
        //	$pageIndex = 1;
        //	$params['pageIndex'] = $pageIndex;
        //} else {
//			$params = Zend_Json::decode($query);
//			$pageIndex = $params['pageIndex'];
//
//			foreach (array('username', 'email', 'role', 'status') as $key) {
//				if (isset($params[$key]) && $params[$key] == '') {
//					$params[$key] = null;
//				}
//			}	$params = Zend_Json::decode($query);
//
//		}
//		$offset   = ($pageIndex > 0) ? ($pageIndex - 1) * $perPage : 0;
//		$users 	  = $userModel->find($offset, $perPage, $params);
        $users = $userModel->getAll();
//		$numUsers = $userModel->count($params);
//
//		/**
//		 * Paginator
//		 */
//		$paginator = new Zend_Paginator(new Rabbit_Utility_PaginatorAdapter($users, $numUsers));
//		$paginator->setCurrentPageNumber($pageIndex);
//		$paginator->setItemCountPerPage($perPage);
        //$this->view->assign('roles', $roles);
        $this->view->assign('users', $users);
        //$this->view->assign('currentUser', Zend_Auth::getInstance()->getIdentity());
        //$this->view->assign('paginator', $paginator);
        //$this->view->assign('paginatorOptions', array(
//			'path' 	   => '',
//			'itemLink' => 'javascript: filterUsers(%d, ' . urlencode(Zend_Json::encode($params)) . ');',
//		));
//		if ($query != '') {
//			$this->_helper->getHelper('viewRenderer')->setNoRender();
//			$this->_helper->getHelper('layout')->disableLayout();
//
//			$content = $this->view->render('user/_filter.phtml');
//			$this->getResponse()->setBody($content);
//		}
    }

    /**
     * Add new user
     *
     * @return void
     */
    public function addAction() {
        $request = $this->getRequest();
        $roleModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getRoleModel();
        $userModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getUserModel();

        $roles = $roleModel->getRoles();
        $this->view->assign('roles', $roles);

        if ($request->isPost()) {
            $password = $request->getPost('password');
            $confirmPassword = $request->getPost('confirm_password');
            if ($password == $confirmPassword && $password != '') {
                $params = array(
                    'username' => $request->getPost('username'),
                    'password' => md5($request->getPost('password')),
                    'full_name' => $request->getPost('full_name'),
                    'email' => $request->getPost('email'),
                    'actived' => 0,
                    'created_date' => date('Y-m-d H:i:s'),
                    'logged_in_date' => null,
                    'is_online' => 0,
                    'role_id' => $request->getPost('role_id')
                );

                $id = $userModel->add($params);
                if ($id > 0) {
                    $this->_helper->getHelper('FlashMessenger')
                            ->addMessage('success:' . $this->view->translate('user_add_success'));
                } else {
                    $this->_helper->getHelper('FlashMessenger')
                            ->addMessage('error:' . $this->view->translate('user_add_error'));
                }
            } else {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('error:' . $this->view->translate('user_confirm_password_error'));
            }
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'core_user_add'));
        }
    }
    /**
     * Edit new user
     *
     * @return void
     */
    public function editAction() {
        $request = $this->getRequest();
        $roleModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getRoleModel();
        $userModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getUserModel();

        $roles = $roleModel->getRoles();
        $this->view->assign('roles', $roles);

        $userId = $request->getParam('id');
        $user = $userModel->getById($userId);
        if (null == $user) {
            throw new Exception('Not found user with id of ' . $userId);
        }
        $this->view->assign('user', $user);
        if ($request->isPost()) {
            $password = $request->getPost('password');
            $confirmPassword = $request->getPost('confirm_password');
            if ($password == $confirmPassword) {
                $params = array(
                    'id'        => $userId,
                    'username' => $request->getPost('username'),
                    'full_name' => $request->getPost('full_name'),
                    'email' => $request->getPost('email'),
                    'role_id' => $request->getPost('role_id')
                );
                if($password != ''){
                    $params['password'] = $password;
                }

                if ($userModel->edit($params)) {
                    $this->_helper->getHelper('FlashMessenger')
                            ->addMessage('success:' . $this->view->translate('user_edit_success'));
                } else {
                    $this->_helper->getHelper('FlashMessenger')
                            ->addMessage('error:' . $this->view->translate('user_edit_error'));
                }
            } else {
                $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('error:' . $this->view->translate('user_confirm_password_error'));
            }
            $this->_redirect($this->view->serverUrl() . $this->view->url(array(), 'core_user_list'));
        }
    }

    /**
     * Check user exist or not
     *
     * @return void
     */
    public function checkAction() {
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        $checkType = $request->getParam('check_type');
        $original = $request->getParam('original');
        $value = $request->getParam($checkType);

        

        $existed = false;
        if ($original == null || ($original != null && $value != $original)) {
            $userModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getUserModel();
            $existed = $userModel->exist($checkType, $value);
        }
        ($existed == true) ? $this->getResponse()->setBody('false') : $this->getResponse()->setBody('true');
    }

    /**
     * Activate or deactive user
     *
     * @return void
     */
    public function activateAction() {
        $this->_helper->getHelper('viewRenderer')->setNoRender();
        $this->_helper->getHelper('layout')->disableLayout();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $id = $request->getPost('id');
            $status = $request->getPost('status');
            $userModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getUserModel();

            /**
             * Do NOT allow user to activate/deactivate himself/herself
             */
            if ($id != Zend_Auth::getInstance()->getIdentity()->id) {
                if ($userModel->toggleStatus($id))
                    $this->getResponse()->setBody('RESULT_OK');
                else
                    $this->getResponse()->setBody('RESULT_ERROR');
            }else {
                $this->getResponse()->setBody('RESULT_DENY');
            }
        }
    }

    public function deleteAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();
        $result = array(
            'status' => 'error',
            'ids' => array()
        );
        if ($request->isPost()) {
            $id = $request->getPost('id');
            $ids = array();
            if (is_numeric($id)) {
                $ids[] = $id;
            } else {
                $ids = Zend_Json::decode($id);
            }

            $userModel = Rabbit_Model_Factory::getInstance()->setModule('core')->getUserModel();
            foreach ($ids as $userId) {
                if($userId != Zend_Auth::getInstance()->getIdentity()->id){
                    $user = $userModel->getById($userId);
                    if ($user != null) {
                        if ($userModel->delete($userId)){
                            $result['status'] = 'ok';
                            $result['ids'][] = $userId;
                        }
                    }
                }
            }
        }
        $this->getResponse()->setBody(Zend_Json::encode($result));
    }

}

?>
